<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/3/28
 * Time: 上午8:54
 * 积分变动操作
 */

namespace app\common\controller;


use app\common\model\CardBonusRule;
use app\common\model\CardCzgive;
use app\common\model\CardMember;
use app\common\model\CardUserGet;
use app\common\model\CardUserLog;
use app\common\model\CardUserUpdate;
use think\Request;
use Wechat\Wxobjopen;

class BonusT extends Wxoption
{

//    public function _initialize(Request $request)
//    {
//        $param = $request->param();
//        $ActionLogs = new ActionLogs();
//        $ActionLogs->writelog("payos","web","bonust","e:",$param);
//    }

    //积分变动充值时调用（无充送规则）
    /*
     * $user 会员卡号code   会员卡card_id    会员卡ID id
     * $arr giveid 充值规则ID(默认传递空)  增加积分add_balance
     *
     * */
    public function cz_bonus_rec($user,$arr)
    {
        try {
            $CardMember = new CardMember();
            $CardUserGet = new CardUserGet();
            //更新积分
            $card = $CardMember->where('card_id', $user['card_id'])->field('supply_bonus,bonus_rule')->find();
            //判断是否开启积分
            if ($card['supply_bonus'] == 1) {
//                if ($arr['giveid'] == '' || $arr['giveid'] == "0" || $arr['giveid'] == null || empty($arr['giveid'])) {
                    $bonus_rule = json_decode($card['bonus_rule'], true);
                    //比例和积分
                    $bili = @($bonus_rule['increase_bonus'] / $bonus_rule['cost_money_unit']);
                    $add_bonus = floor($arr['add_balance'] * $bili);
                    //同步微信数据
                    $bonus['code'] = $user['code'];
                    $bonus['card_id'] = $user['card_id'];
                    $bonus['record_bonus'] = '充值赠送';
                    $bonus['bonus'] = $add_bonus;
                    $resu['bonus'] = $this->updatebonus($bonus);
                    //判断更新
                    if ($resu['bonus']['errcode'] == 0) {
                        //更新积分
//                        $datas['add_bonus'] = $add_bonus;
//                        $datas['record_bonus'] = '充值赠送';
                        $CardUserGet->where('id', $user['id'])->setField('bonus', $resu['bonus']['result_bonus']);
                        $bonusdata = $resu;
                        $bonusdata['code'] = 0;
                        $bonusdata['message'] = $resu;
                        $bonusdata['add_bonus'] = $add_bonus;
                        //写入积分记录
                        $this->rec_user($user,$arr,$bonus);
                    } else {
                        $bonusdata = ['code' => 9005, 'message' => $resu,'add_bonus'=>$add_bonus];

                    }
//                }else{
//                    $bonusdata = ['code' => 9004, 'message' =>'无积分','add_bonus'=>''];
//                }
            }else{
                $bonusdata = ['code' => 9004, 'message' => '无积分','add_bonus'=>''];
            }
        } catch (\Exception $e) {
            $bonusdata = ['code' => 9999, 'message' => $e->getMessage()];
        }
        return $bonusdata;
    }

    public function rec_user($user,$arr,$bonus){
        try {
            $CardMember = new CardMember();
            $bonusb['con_username'] = $arr['username'];
            $bonusb['record_bonus'] = $arr['record_balance'];
            $bonusb['us_id'] = $user['id'];
            $bonusb['top_mid'] = $user['top_mid'];
            $bonusb['mid'] = $user['mid'];
            $bonusb['c_id'] = $CardMember->where(['card_id' => $user['card_id']])->value('id');
            $bonusb['openid'] = $user['openid'];
            $bonusb['card_id'] = $user['card_id'];
            $bonusb['code'] = $user['code'];
            $bonusb['reason'] = 2;
            $bonusb['bonus'] = $bonus['bonus'];
            $bonusb['pay_cate'] = 4;
            $bonusb['cate'] = 2;
            $bonusb['source'] = $arr['source'];
            $bonusb['orderid'] = $arr['orderid'];
//            file_put_contents('/data2/html/payos/rec_user_bonus.txt', '0:' . json_encode($bonusb) . PHP_EOL, FILE_APPEND);
            $UserBonusFee = new UserBonusFee();
            $UserBonusFee->rec_user_bonus($bonusb, 1);
        }catch (\Exception $e) {
                $bonusdata = ['code' => 9999, 'message' => $e->getMessage()];
//            file_put_contents('/data2/html/payos/rec_user_bonus.txt', '0-1:' . json_encode($bonusdata) . PHP_EOL, FILE_APPEND);
            }
    }
    //积分变动 冲送用
    /*
     * $user 会员卡号code   会员卡card_id    会员卡ID id
     * $arr giveid 充值规则ID(默认传递空)  增加积分add_balance
     *
     * */
    public function cs_bonus_rec($user)
    {
        try {
            $CardMember = new CardMember();
            $card = $CardMember->where('card_id', $user['card_id'])->find();
            if ($card['supply_bonus'] == 1) {
//                if ($user['giveid'] !== '') {
                    $CardCzgive = new CardCzgive();
                    $CardUserGet = new CardUserGet();
                    $zs_bonus = $CardCzgive->where('id', $user['giveid'])->value('bonus');
                    if ($zs_bonus > 0) {
                        //同步微信数据
                        $bonusb['code'] = $user['code'];
                        $bonusb['card_id'] = $user['card_id'];
                        $bonusb['record_bonus'] = '充值赠送';
                        $bonusb['bonus'] = $zs_bonus;
                        $resut = $this->updatebonus($bonusb);
                        if ($resut['errcode'] == 0) {
                            //更新积分
                            $CardUserGet->where('id', $user['id'])->setField('bonus', $resut['result_bonus']);
                            $bonusdata = ['code' => 0, 'message' => '赠送成功！','add_bonus'=>$zs_bonus];
                            //写入积分记录
                            $CardMember = new CardMember();
//                            $users = $CardUserGet->where('id', $user['id'])->field('id,top_mid,openid')->find();
                            $bonusb['us_id'] = $user['id'];
                            $bonusb['top_mid'] = $user['top_mid'];
                            $bonusb['mid'] = $user['mid'];
                            $bonusb['c_id'] = $CardMember->where(['card_id'=>$user['card_id']])->value('id');
                            $bonusb['openid'] = $user['openid'];
                            $bonusb['reason'] = $user['reason'];
                            $bonusb['pay_cate'] = 4;
                            $bonusb['con_username'] = $user['con_username'];
                            $bonusb['cate'] = 2;
                            $bonusb['reason'] = 2;
                            $bonusb['source'] = 1;
                            $bonusb['orderid'] = $user['orderid'];
//                            file_put_contents('/data2/html/payos/rec_user_bonus.txt', '0:' . json_encode($bonusb).PHP_EOL, FILE_APPEND);
                            $UserBonusFee = new UserBonusFee();
                            $UserBonusFee->rec_user_bonus($bonusb,1);

                        } else {
                            $bonusdata = ['code' => 9001, 'message' => '赠送失败！','add_bonus'=>$zs_bonus];
                        }
                    } else {
                        $bonusdata = ['code' => 9002, 'message' => '无赠送积分！','add_bonus'=>''];

                    }
//                }else{
//                    $bonusdata = ['code' => 9004, 'message' =>'无积分','add_bonus'=>''];
//                }
            }else{
                $bonusdata = ['code' => 9004, 'message' =>'无积分','add_bonus'=>''];
            }
        } catch (\Exception $e) {
            $bonusdata = ['code' => 9999, 'message' => $e->getMessage(),'add_bonus'=>''];
        }
        return $bonusdata;
    }

    //积分变动增加
    /*
     * id / record_bonus /  bonus  /   hx_fs  /  type  /  cate /  reason  /  source  /  mid  /  username
     * */
    public function add_bonus_rec($arr)
    {
        //同步微信数据
        try {
            $CardUserGet = new CardUserGet();
            $user = $CardUserGet->where(['id' => $arr['id']])->field('code,card_id,id,mid,top_mid,openid')->find();
            $CardMember = new CardMember();
            $card = $CardMember->where(['card_id'=>$user['card_id']])->field('id')->find();
            $bonus['code'] = $user['code'];
            $bonus['card_id'] = $user['card_id'];
            $bonus['record_bonus'] = $arr['record_bonus'];
            $bonus['bonus'] = $arr['bonus'];
            $resu = $this->updatebonus($bonus);
            if ($resu['errcode'] == 0) {
                $map['card_id'] = $user['card_id'];
                $map['code'] = $user['code'];
                $res = $CardUserGet->where($map)->setField('bonus', $resu['result_bonus']);
                if ($res) {
                    $CardUserUpdate = new CardUserUpdate();
                    $datas['code'] = $user['code'];
                    $datas['card_id'] = $user['card_id'];
                    $datas['openid'] = $user['openid'];
                    $datas['record_bonus'] = $arr['record_bonus'];
                    $datas['hx_fs'] = $arr['hx_fs'];            //方式
                    $datas['type'] = $arr['type'];             //类型
                    $datas['cate'] = $arr['cate'];             //类别
                    $datas['reason'] = $arr['reason'];           //原因
                    $datas['source'] = $arr['source'];           //来源
                    $datas['mid'] = $arr['mid'];
                    $datas['add_bonus'] = $arr['bonus'];
                    $datas['con_username'] = $arr['username'];
                    $datas['create_time'] = time();
                    $CardUserUpdate->allowField(true)->save($datas);
                    $record_id = $CardUserUpdate->id;
                    //carduserlog 记录
                    $datas['up_id'] = $record_id;
                    $datas['bonus'] = $arr['bonus'];
                    $datas['c_id'] = $card['id'];
                    $datas['us_id'] = $user['id'];
                    $datas['top_mid'] = $user['top_mid'];
                    $datas['mid'] = $user['mid'];
                    $datas['pay_cate'] = $arr['hx_fs'];
                    $UserBonusFee = new UserBonusFee();
                    $UserBonusFee->rec_user_bonus($datas,1);
                    $rarr = ['code' => '0', 'message' => '增加成功！','record_id'=>$record_id];
                } else {
                    $rarr = ['code' => '9001', 'message' => '增加失败！'];
                }
            } else {
                $rarr = ['code' => '9002', 'message' => '增加失败！'];
            }
        } catch (\Exception $e) {
            $rarr = ['code' => 9999, 'message' => $e->getMessage()];
        }
        return $rarr;
    }

    //积分变动核销用
    /*
     * id / record_bonus /  bonus  /   hx_fs  /  type  /  cate /  reason  /  source  /  mid  /  username
     * */
    public function hx_bonus_del($arr)
    {
//        $arr['record_bonus'] = '后台核销';
        //同步微信数据
        try {
            $CardUserGet = new CardUserGet();
            $user = $CardUserGet->where(['id' => $arr['id']])->field('code,card_id,id,openid,top_mid,mid')->find();
            $CardMember = new CardMember();
            $card = $CardMember->where(['card_id'=>$user['card_id']])->field('id')->find();
            $bonus['code'] = $user['code'];
            $bonus['card_id'] = $user['card_id'];
            $bonus['record_bonus'] = $arr['record_bonus'];
            $bonus['bonus'] = -$arr['bonus'];
            $resu = $this->updatebonus($bonus);
            if ($resu['errcode'] == 0) {
                $map['card_id'] = $user['card_id'];
                $map['code'] = $user['code'];
                $res = $CardUserGet->where($map)->setField('bonus', $resu['result_bonus']);
                if ($res) {
                    $CardUserUpdate = new CardUserUpdate();
                    $datas['code'] = $user['code'];
                    $datas['card_id'] = $user['card_id'];
                    $datas['openid'] = $user['openid'];
                    $datas['record_bonus'] = $arr['record_bonus'];
                    $datas['hx_fs'] = $arr['hx_fs'];            //方式
                    $datas['type'] = $arr['type'];             //类型
                    $datas['cate'] = $arr['cate'];             //类别
                    $datas['reason'] = $arr['reason'];           //原因
                    $datas['source'] = $arr['source'];           //来源
                    $datas['mid'] = $arr['mid'];
                    $datas['del_bonus'] = $arr['bonus'];
                    $datas['con_username'] = $arr['username'];
                    $datas['create_time'] = time();
                    $CardUserUpdate->allowField(true)->save($datas);
                    $record_id = $CardUserUpdate->id;
                    //carduserlog 记录
                    $datas['up_id'] = $record_id;
                    $datas['bonus'] = $arr['bonus'];
                    $datas['c_id'] = $card['id'];
                    $datas['pay_cate'] = $arr['hx_fs'];
                    $datas['top_mid'] = $user['top_mid'];
                    $datas['mid'] = $user['mid'];
                    $datas['us_id'] = $user['id'];
                    $UserBonusFee = new UserBonusFee();
                    $UserBonusFee->rec_user_bonus($datas,1);
                    $rarr = ['code' => '0', 'message' => '核销成功！','record_id'=>$record_id];
                } else {
                    $rarr = ['code' => '9001', 'message' => '更新失败！'];
                }
            } else {
                $rarr = ['code' => '9003', 'message' => '核销失败！'];
            }
        } catch (\Exception $e) {
            $rarr = ['code' => 9099, 'message' => $e->getMessage()];
        }
        return $rarr;
    }

    /*
   * 积分规则
   * card_id(会员卡ID)，add_bonus(变动积分)，record_bonus（变动说明）code（用户会员卡编号）
   *
   */
    public function bonusgive($arr)
    {
        try {
            $CardBonusRule = new CardBonusRule();
//        $arr = [];
            //禁止规则
            $map['end_time'] = ['egt', time()];
            $map['card_id'] = $arr['card_id'];
            $map['type'] = 1;
            $map['statu'] = 0;
            $ruledis = $CardBonusRule->where($map)->find();
            if (empty($ruledis)) {
                //多倍规则
                $mab['end_time'] = ['egt', time()];
                $mab['card_id'] = $arr['card_id'];
                $mab['type'] = 2;
                $mab['statu'] = 0;
                $rulemax = $CardBonusRule->where($mab)->find();
//                var_dump($CardBonusRule->getLastSql());
                //多倍积分
                if ($rulemax) {
                    $CardUserGet = new CardUserGet();
                    $barr['add_bonus'] = $arr['add_bonus'] * $rulemax['bonus_max'];               //积分变动
                    $barr['card_id'] = $arr['card_id'];                                         //卡券ID
                    $barr['code'] = $arr['code'];                                               //卡券CODE
                    $barr['bonus'] = $barr['add_bonus'];
                    $barr['record_bonus'] = $arr['record_bonus'];                               //说明
                    $res = $this->updatebonus($barr);
                    if ($res['errcode'] == 0) {
                        $mad['card_id'] = $arr['card_id'];
                        $mad['code'] = $arr['code'];
                        $CardUserGet->where($mad)->setField('bonus', $res['result_bonus']);
                        $datas = $res;
                        $datas['add_bonus'] = $arr['add_bonus'];
                    } else {
                        $datas = ['msg' => $res['errmsg'], 'code' => '9002', 'add_bonus' => $arr['add_bonus']];
                    }
                    //普通积分
                } else {
                    $CardUserGet = new CardUserGet();
                    $barr['add_bonus'] = $arr['add_bonus'];               //积分变动
                    $barr['card_id'] = $arr['card_id'];                                         //卡券ID
                    $barr['code'] = $arr['code'];                                               //卡券CODE
                    $barr['record_bonus'] = $arr['record_bonus'];                               //说明
                    $barr['bonus'] = $barr['add_bonus'];
                    $res = $this->updatebonus($barr);
                    if ($res['errcode'] == 0) {
                        $mad['card_id'] = $arr['card_id'];
                        $mad['code'] = $arr['code'];
                        $CardUserGet->where($mad)->setField('bonus', $res['result_bonus']);
                        $datas = $res;
                        $datas['add_bonus'] = $arr['add_bonus'];
                    } else {
                        $datas = ['msg' => $res['errmsg'], 'code' => '9002', 'add_bonus' => $arr['add_bonus']];
                    }
                }
            } else {
                $datas = ['msg' => '该时间段内不可积分', 'code' => '9004', 'add_bonus' => 0];
            }
        }catch (\Exception $e) {
            $datas = ['code' => 9999, 'message' => $e->getMessage()];
        }
        return $datas;
    }


    //核销方法无通知 全量更新
    public function hxbonusnotz($arr)
    {
        try {
            $CardUserGet = new CardUserGet();
            $map['id'] = $arr['id'];
            $user = $CardUserGet->where($map)->find();
            $options = $this->options($user['card_id']);
            $WxObj = new Wxobjopen($options);
            $data['code'] = $user['code'];
            $data['card_id'] = $user['card_id'];
            $data['bonus'] = $arr['bonus'];                     //积分全量   填300则不论之前有多少积分只剩300
            $data['notify_optional']['is_notify_bonus'] = false;
            $data['notify_optional']['is_notify_balance'] = false;
            $data['notify_optional']['is_notify_custom_field1'] = false;
            $res = $WxObj->updateUserInfo($data);

        } catch (\Exception $e) {
            $res = ['code' => 9999, 'message' => $e->getMessage()];
        }
        return json($res);
    }

    //积分更新微信操作
    public function updatebonus($arr)
    {
        try {
            //实例化微信
            $options = $this->options($arr['card_id']);
            $WxObj = new Wxobjopen($options);
            $data = [
                'code' => $arr['code'],
                'card_id' => $arr['card_id'],
//                'record_bonus' => $arr['record_bonus'],       //说明
                'add_bonus' => $arr['bonus'],             //积分变动值  负数为减少
                'notify_optional' => [
                    'is_notify_bonus' => true,
                    'is_notify_balance' => false,
                    'is_notify_custom_field1' => false,
                ],
            ];
            $res = $WxObj->updateUserInfo($data);

            if ($res['errcode'] == 0){
                $Level = new Level();
                $Level->checklevel($arr['card_id'],$arr['code'],$res['result_bonus']);
            }

        } catch (\Exception $e) {
            $res = ['errcode' => 9099, 'message' => $e->getMessage()];
        }
        return $res;
    }

    //记录表
    public function rec_cardlogs($arr)
    {
        try {
            $CardUserLog = new CardUserLog();
            $data['mid'] = $arr['mid'];
            $data['top_mid'] = $arr['top_mid'];
            $data['up_id'] = $arr['up_id'];
            $data['c_id'] = $arr['c_id'];
            $data['us_c_id'] = $arr['us_c_id'];
            $data['openid'] = $arr['openid'];
            $data['con_username'] = $arr['con_username'];
            $data['card_id'] = $arr['card_id'];
            $data['code'] = $arr['code'];
            if (isset($arr['add_bonus'])) {
                $data['num'] = $arr['add_bonus'];
            }
            if (isset($arr['del_bonus'])) {
                $data['num'] = -$arr['del_bonus'];
            }
            if (isset($arr['record_bonus'])){
                $data['record'] = $arr['record_bonus'];           //记录
            }
            if (isset($arr['orderid'])) {
                $data['orderid'] = $arr['orderid'];
            }
            $data['type'] = $arr['type'];               //1充值/2核销
            $data['cate'] = $arr['cate'];               //1积分/2余额
            $data['reason'] = $arr['reason'];           //原因
            $data['source'] = $arr['source'];           //来源
            $data['create_time'] = time();
            $res = $CardUserLog->allowField(true)->save($data);
        }catch (\Exception $e) {
            $res = ['errcode' => 9999, 'message' => $e->getMessage()];
        }
//        file_put_contents('/data2/html/payos/test.txt', 'bonus-1' . json_encode($res), FILE_APPEND);
    }

}